<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Online;
use App\Connect;
use App\Account;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class MonitorController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }


    //在线状态监测
    public function index($key)
    {
    	if ($key != '98765432100'){
    		echo("呵呵");die();
    	}
      $TOKEN_VALIDITY = env("TOKEN_VALIDITY");
    	$date = date('Y-m-d H:i:s',time()-$TOKEN_VALIDITY);
    	$online = Online::count();
    	$online_expired = Online::where('updated_at','<',$date)->count();
    	$connect = Connect::count();
    	$connect_expired = Connect::where('updated_at','<',$date)->count();
    	$account = Account::sum('terminal_total');
    	$account_used = Account::sum('terminal_used');

    	echo "在线人数：$online <br />
    		无效在线人数：$online_expired <br />
    		连接数：$connect <br />
    		无效连接数：$connect_expired <br />
    		账户数：$account <br />
    		已用账户数：$account_used <br />
    		<br />
    		<a href='http://api.niumoip.com/v1/monitor/recovery/9'>清理》》</a>
    	";

    }

    //资源回收
    public function recovery($key) {
    	if ($key != '12345678900'){
    		echo("呵呵");die();
    	}
		$TOKEN_VALIDITY = env("TOKEN_VALIDITY");
		if(!$TOKEN_VALIDITY){
			$TOKEN_VALIDITY = 900;
		}
    	$date = date('Y-m-d H:i:s',time()-$TOKEN_VALIDITY);
    	$online_expired = Online::where('updated_at','<',$date)->get();
    	if (count($online_expired)>0){
    		foreach ($online_expired as $ol){
    			$ol->delete();
    		}
    	}
    	$connect = Connect::count();
    	$account_used = Account::sum('terminal_used');
    	if ($connect != $account_used){
    		echo("连接数不匹配，速请大神手动检测");die();
    	}

    	$connect_expired = Connect::where('updated_at','<',$date)->get();
    	foreach($connect_expired as $con){
    		$account = Account::find($con->account_id);
    		$account->terminal_used = $account->terminal_used-1;
    		$account->save();
    		$con->delete();
    	}

    	echo "清理完毕......";
    }

}
